package gridWorld;


import java.io.*;
import java.util.ArrayList;
import java.util.Collections;

import dataGeneration.GenerateStorySpace;
import PPCA.*;
import prefix.*;

import no.uib.cipr.matrix.*;

public class TestGridWorld {
	static int getRecommend(Matrix predict, double[][] mask, ArrayList<Prefix> prefixList, int currentID){
		double max = -10;
		int maxID = 0;
		while(true){
			for(int i = 0; i < predict.numRows(); i++){
				if(predict.get(i, 0) > max){
					max = predict.get(i, 0);
					maxID = i;
				}
				
			}
			predict.set(maxID, 0, -100);
			if(mask[currentID][maxID] != 0 && prefixList.get(maxID).itemList.size() > prefixList.get(currentID).itemList.size()){
				break;
			}
			max = -10;
		}
		
		
		return maxID;
		
	}
	
	public static void main(String[] args) {
		String line = null;
		ArrayList<Prefix> prefixList = PrefixListOperation.readPrefixList("PrefixList.txt", 1);
		System.out.println("Loading data...");
		DenseMatrix cov = new DenseMatrix(MyUtil.readData("cov1.txt", false));
		DenseMatrix mean = new DenseMatrix(MyUtil.readData("mean1.txt", false));
		DenseMatrix current = new DenseMatrix(cov.numColumns(), 1);
		double[][] mask = MyUtil.readData("Mask.txt", false);
		System.out.println("Finished!\nInput:\n");
		try{
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			line = br.readLine();
			
			while(line != ""){
				line = line.trim();
				String[] vs = line.split(" ");
				double[] data = new double[vs.length-1];
				int label = 0;
				try{
					for(int i = 1; i < vs.length; i++){
						data[i-1] = Integer.parseInt(vs[i]);
					}
				
					label = Integer.parseInt(vs[0].substring(0, vs[0].length()-1));
				}
				catch(Exception e){
					System.out.println("Format exception: Wrong Input! Try again:");
					line = br.readLine();
					continue;
				}
				int id = Collections.binarySearch(prefixList, new Prefix(data));
				if(id < 0){
					System.out.println("Cannot find the prefix! Try again:");
					line = br.readLine();
					continue;
				}
				current.set(id, 0, label);
				if(data[data.length-1] == GenerateStorySpace.gridSize*GenerateStorySpace.gridSize || data.length == prefixList.get(prefixList.size()-1).itemList.size()){
					System.out.println("Finished!");
					line = br.readLine();
					continue;
				}
				Matrix predict =  PPCA.ppca_test(cov, mean, current);
				int recommend = getRecommend(predict, mask, prefixList, id);
				System.out.println(prefixList.get(recommend).itemList);
				line = br.readLine();
			}
		}
		catch(Exception e){
			e.printStackTrace();
		}
		
	}
}
